//
//  GSDataBaseManager.m
//  GameSky
//
//  Created by lanou on 16/1/28.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSDataBaseManager.h"
#import "GSSubscrebe_Add_Topic.h"

@interface GSDataBaseManager ()

@property (nonatomic, strong) FMDatabase *db;

@end

@implementation GSDataBaseManager
/**
 *  单例初始化方法
 */
+ (GSDataBaseManager *)sharedDataBase
{
    static GSDataBaseManager *DBManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        DBManager = [[GSDataBaseManager alloc] init];
    });
    return DBManager;
}

/**
 *  获取数据库已订阅数据;
 */
- (NSMutableArray *)subscribeDataFromDataBase
{
    // 1.拼接获得数组库路径;
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *dataPath = [[path stringByAppendingPathComponent:@"data"]stringByAppendingPathComponent:@"GSDataBase.db"];
    
    // 2.打开数据库;
    _db = [FMDatabase databaseWithPath:dataPath];
    if (![_db open]) {
        NSLog(@"数据库打开失败");
    }
    
    // 3.初始化可变数组添加数据;
    NSMutableArray *dataArray = [NSMutableArray array];
    FMResultSet *result = [_db executeQuery:@"select * from SubscribeList"];
    while ([result next]) {
        NSString *nodeIds = [result stringForColumn:@"nodeIds"];
        NSString *sourceName = [result stringForColumn:@"sourceName"];
        NSNumber *cnt = [NSNumber numberWithInt:[result intForColumn:@"cnt"]];
        NSData *imageData = [result dataForColumn:@"imageData"];
        
        GSSubscrebe_Add_Topic *model = [[GSSubscrebe_Add_Topic alloc] init];
        model.sourceName = sourceName;
        model.imageModel = [UIImage imageWithData:imageData];
        model.sourceId = nodeIds;
        model.cnt = cnt;
        [dataArray addObject:model];
    }
    return dataArray;
}

@end
